package comp.movel.ubiqua;

import java.io.IOException;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import comp.movel.ubiqua.bd.RankingDAO;
import comp.movel.ubiqua.ws.ConexaoWebService;
import comp.movel.ubiqua.ws.JogadorWSDL;

public class PassaOuRepassaActivity extends Activity {

	// Intent request codes
	public static final int REQUEST_CONNECT_DEVICE = 1;
	public static final int REQUEST_ENABLE_BT = 2;
	public static final int DISCOVERY_REQUEST = 0;

	private BluetoothAdapter mBluetoothAdapter = null;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menuprincipal);
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (TemConexao()){
            Toast.makeText(getApplicationContext(), "Tem Conexao", Toast.LENGTH_SHORT).show();
        }else{
        	Toast.makeText(getApplicationContext(), "Sem Conexao", Toast.LENGTH_SHORT).show();
        }
	}

	public void jogar(View v) {
		if (!mBluetoothAdapter.isEnabled()) {
			Intent enableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
			// Otherwise, setup the chat session
		} else {
			iniciarJogo();
		}
	}

	public void verRankingGlobal(View v) {
		ArrayList<JogadorWSDL> ranking = null;
		try {
			ranking = ConexaoWebService.recebeRanking();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Toast.makeText(getApplicationContext(),
					getResources().getString(R.string.erro1),
					Toast.LENGTH_SHORT).show();
			return;
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Toast.makeText(getApplicationContext(),
					getResources().getString(R.string.erro2),
					Toast.LENGTH_SHORT).show();
			return;
		}
		mostrarRanking(ranking);
	}

	public void verRankingLocal(View v) {
		RankingDAO ranking = new RankingDAO(getApplicationContext());
		mostrarRanking(ranking.receberRanking());
	}

	public void mostrarRanking(ArrayList<JogadorWSDL> ranking) {
		String resultado = "";
		if (ranking != null && ranking.size() > 0) {
			for (int i = 0; i < ranking.size(); i++) {
				resultado += (i + 1) + " - " + ranking.get(i).getProperty(0)
						+ " - " + ranking.get(i).getProperty(1) + "Pts\n";
			}
		}else{
			resultado = "Ranking Vazio!";
		}
		AlertDialog alertDialog;
		alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setTitle("Ranking - TOP 5");
		alertDialog.setMessage(resultado);
		alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				dialog.dismiss();
			}
		});
		alertDialog.show();
	}

	public void Sair(View v) {
		finish();
	}
	
	private boolean TemConexao() { 
        boolean lblnRet = false;
        try
        {
            ConnectivityManager cm = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE); 
            if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) { 
                lblnRet = true; 
            } else { 
                lblnRet = false; 
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return lblnRet;
    }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (resultCode) {
		case 0:
			Toast.makeText(getApplicationContext(), "Sem acesso a bluetooth",
					Toast.LENGTH_SHORT).show();
			break;
		case -1:
			iniciarJogo();
			break;

		default:
			break;
		}
		Log.e("request", "" + requestCode);
		Log.e("result", "" + resultCode);
	}

	private void iniciarJogo() {
		Intent i = new Intent(this, JogoActivity.class);
		startActivity(i);
	}

}